import React, { useReducer } from 'react';
import utils from '../../utils';
import { history } from 'umi';
import FormBuild from '../../../../lib/';
import _set from 'lodash/set';
import _cloneDeep from 'lodash/cloneDeep';
import _camelCase from 'lodash/camelCase';
const { FormBuilder } = FormBuild;
const { storage } = utils;
import styles from './edit.less';

const getOld = (id: String | Number | undefined) => {
  const oldArr = storage.get('formio_demo_save') || [];
  const oldVal = oldArr.find((i) => i.id == id);
  return oldVal;
};

const reducer = (form: any, item: any) => {
  const { type, value } = item;
  const formCopy = _cloneDeep(form);
  switch (type) {
    case 'formChange':
      for (let prop in value) {
        // eslint-disable-next-line no-prototype-builtins
        if (value.hasOwnProperty(prop)) {
          form[prop] = value[prop];
        }
      }
      return form;
    case 'replaceForm':
      return _cloneDeep(value);
    case 'title':
      if (type === 'title' && !form._id) {
        formCopy.name = _camelCase(value);
        formCopy.path = _camelCase(value).toLowerCase();
      }
      break;
    default:
      return form;
  }
  _set(formCopy, type, value);
  return formCopy;
};

export default function DeditPage(props: Props) {
  const params = props.match && props.match.params ? props.match.params : {};
  const isNew = params && params.id ? false : true;
  const id = isNew ? Math.random().toString(36).slice(-6) : params.id;
  let components;

  if (!isNew) {
    const oldVal = getOld(id);
    if (oldVal && oldVal.schema) components = oldVal.schema.components || [];
  }

  const _form = { id, components };

  const [form, dispatchFormAction] = useReducer(reducer, _cloneDeep(_form));

  const saveForm = () => {
    const { id, components } = form;
    const name = new Date().toLocaleString();
    const object: ListData = { id, name, schema: { components } };
    let oldArr = storage.get('formio_demo_save');

    if (oldArr && oldArr.length) {
      let oldValIndex = oldArr.findIndex((i) => i.id == id);
      if (oldValIndex >= 0) oldArr.splice(oldValIndex, 1);
    } else {
      oldArr = [];
    }
    oldArr.push(object);
    storage.set('formio_demo_save', oldArr);

    if (isNew) {
      history.push(`/list`);
    }
  };

  const preveiw = () => {
    history.push(`/detail/${form.id}`);
  };

  const formChange = (newForm: any) =>
    dispatchFormAction({ type: 'formChange', value: newForm });

  return (
    <div className={styles.formBox}>
      <div className={styles.top}>
        <span className="btn btn-primary" onClick={() => saveForm()}>
          保存
        </span>
        <span className="btn btn-primary" onClick={() => preveiw()}>
          预览
        </span>
      </div>
      <FormBuilder
        key={form.id}
        form={form}
        options={{ language: 'zh' }}
        onChange={formChange}
      ></FormBuilder>
    </div>
  );
}
